package me.luger.project.fof.service;

import me.luger.core.commom.util.CommandResult;
import me.luger.core.commom.util.ShellUtil;
import me.luger.core.dao.nutz.entity.page.Pagination;
import me.luger.core.dao.nutz.service.BaseService;
import me.luger.project.fof.config.cache.redis.RedisManager;
import me.luger.project.fof.entity.FofInfo;
import me.luger.project.fof.entity.FundInfo;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Repository
public class FofInfoService extends BaseService<FofInfo> {

    @Autowired
    private FundInfoService fundInfoService;

    @Autowired
    private FofCollectService fofCollectService;

    @Autowired
    private RedisManager redisManager;

    public FofInfoService(Dao dao) {
        super(dao);
    }


    public FofInfo insertFofInfo(FofInfo fofInfo){
        fofInfo = this.insert(fofInfo);
        Integer fofId = fofInfo.getId();
        Integer userId = fofInfo.getUserId();
        Double createTime = fofInfo.getCreateDate().getTime() + 0D;
        redisManager.zadd("fof:user:fof:all:"+userId,createTime,String.valueOf(fofId));
        redisManager.zadd("fof:user:fof:private:"+userId,createTime,String.valueOf(fofId));
        redisManager.zadd("fof:user:fof:my:"+userId,createTime,String.valueOf(fofId));
        return fofInfo;
    }

    public void deleteFofInfo(Integer fofId,Integer userId){
        this.delete(new Integer[]{fofId});
        redisManager.zrem("fof:user:fof:all:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:private:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:my:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:public:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:company:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:specify:"+userId,String.valueOf(fofId));
        redisManager.zrem("fof:user:fof:share:"+userId,String.valueOf(fofId));
    }

    public Pagination<FofInfo> getUserAllFof(Integer userId,int pn,int rn){
        Sql sql = Sqls.create("select fof.id,fof.fullName,fof.shortName,fof.profitType,fof.createDate,fof.status,fof.userId," +
                "user.name as owner,pro.name as productTypeName,company.name as companyName from `fof_info` fof " +
                "left join fof_user_info user on fof.`userId` = user.id " +
                "LEFT JOIN fof_company company ON user.`companyId` = company.`id` " +
                "left join fof_product_type pro on fof.`productType` = pro.id " +
                "where fof.`userId` = @userId");
        sql.params().set("userId", userId);
        Pagination<FofInfo> fofInfoPagination = this.listPage(pn,rn,sql);
        List<FofInfo> fofInfoList = fofInfoPagination.getList();
        for(FofInfo fofInfo : fofInfoList){
            int fofId = fofInfo.getId();
            FundInfo fundInfo = fundInfoService.getFundInfo(String.format("%06d", fofId)+".FOF");
            if(null != fundInfo){
                fofInfo.setMarketWorth(0D);
                fofInfo.setNetWorth(fundInfo.getUnitNav());
                fofInfo.setHuiche(fundInfo.getDrawdown());
                fofInfo.setYearProfit(fundInfo.getYieldAnnually());
                fofInfo.setCurYearProfit(fundInfo.getYield1y());
            }else{
                fofInfo.setMarketWorth(10D);
                fofInfo.setNetWorth(34D);
                fofInfo.setHuiche(3D);
                fofInfo.setYearProfit(7D);
                fofInfo.setCurYearProfit(6D);
            }

        }
        return fofInfoPagination;
    }

    /**
     * FOF可见度
     * 1-完全公开
     * 2-公司内部可见
     * 3-只有指定用户可见
     * 4-私有，只有owner可见
     * @param userId
     * @param type
     * @param pn
     * @param rn
     * @return
     */
    public Pagination<FofInfo> getUserFofByType(Integer userId,Integer type,int pn,int rn){
        String redisKey = "";
        if(type == 0){
            redisKey = "fof:user:fof:all:" + userId;
        }else if(type == 1){
            redisKey = "fof:user:fof:public:" + userId;
        }else if(type == 2){
            redisKey = "fof:user:fof:company:" + userId;
        }else if(type == 3){
            redisKey = "fof:user:fof:specify:" + userId;
        }else if(type == 4){
            redisKey = "fof:user:fof:private:" + userId;
        }else if(type == 5){//用户收藏的fof
            redisKey = "fof:user:fof:collect:" + userId;
        }else if(type == 101){//别人共享的
            redisKey = "fof:user:fof:share:" + userId;
        }else if(type == 102){//自己创建的
            redisKey = "fof:user:fof:my:" + userId;
        }

        long start = (pn-1) * rn;
        long end = start + rn - 1;
        Set<String> fofIdSet = redisManager.zrevrange(redisKey,start,end);

        FofInfo fofInfo = null;
        List<FofInfo> fofInfoList = new ArrayList<FofInfo>();
        if(null != fofIdSet){
            for(String fofId : fofIdSet){
                fofInfo = this.getFofFullInfo(Integer.parseInt(fofId));
                if(null == fofInfo){
                    continue;
                }
                FundInfo fundInfo = fundInfoService.getFundInfo(String.format("%06d", Integer.parseInt(fofId))+".FOF");
                if(null != fundInfo){
                    Double fundMarketWorth = fofInfo.getMarketWorth();
                    if(null != fundMarketWorth){
                        fofInfo.setMarketWorth(fundMarketWorth*fundInfo.getUnitNav());
                    }else{
                        fofInfo.setMarketWorth(0D);
                    }
                    fofInfo.setNetWorth(fundInfo.getUnitNav());
                    fofInfo.setHuiche(fundInfo.getDrawdown());
                    fofInfo.setYearProfit(fundInfo.getYieldAnnually());
                    fofInfo.setCurYearProfit(fundInfo.getYield1y());
                }else{
                    fofInfo.setMarketWorth(10000D);
                    fofInfo.setNetWorth(1D);
                    fofInfo.setHuiche(0D);
                    fofInfo.setYearProfit(0D);
                    fofInfo.setCurYearProfit(0D);
                }
                fofInfoList.add(fofInfo);
            }
        }

        Pagination<FofInfo> pagination = new Pagination<FofInfo>();
        pagination.setList(fofInfoList);
        pagination.setPageNo(pn);
        pagination.setPageSize(rn);
        pagination.setTotalCount(redisManager.zcard(redisKey).intValue());
        return pagination;
    }

    /**
     * 获取FOF的基本信息
     * @param fofId
     * @return
     */
    public FofInfo getFofInfo(Integer fofId){
        Sql sql = Sqls.create("select fof.id,fof.fullName,fof.shortName,fof.profitType,fof.createDate,fof.status from `fof_info` fof " +
                "where fof.`id` = @fofId");
        sql.params().set("fofId", fofId);
        List<FofInfo> fofInfoList = this.list(sql);
        if(fofInfoList != null && fofInfoList.size() > 0) {
            return fofInfoList.get(0);
        }
        return null;
    }

    /**
     * 获取FOF的基本信息
     * @param fofId
     * @return
     */
    public FofInfo getFofFullInfo(Integer fofId){
        Sql sql = Sqls.create("SELECT fof.id, fof.fullName, fof.shortName, fof.profitType, fof.createDate,fof.marketWorth,fof.userId\n" +
                "\t, fof.status, user.username AS owner, pro.name AS productTypeName,company.name as companyName\n" +
                "FROM `fof_info` fof\n" +
                "\tLEFT JOIN fof_user_info user ON fof.`userId` = user.id\n" +
                "\tLEFT JOIN fof_company company ON user.`companyId` = company.`id`\n" +
                "\tLEFT JOIN fof_product_type pro ON fof.`productType` = pro.id\n" +
                "WHERE fof.`id` = @fofId");
        sql.params().set("fofId", fofId);
        List<FofInfo> fofInfoList = this.list(sql);
        if(fofInfoList != null && fofInfoList.size() > 0) {
            return fofInfoList.get(0);
        }
        return null;
    }

    /**
     * 更改用户创建基金的可见性
     * @param fofId
     * @param status
     * @return
     */
    public boolean changeStatus(int fofId,int status){
        FofInfo fofInfo = new FofInfo();
        fofInfo.setId(fofId);
        fofInfo.setStatus(status);
        return this.updateIgnoreNull(fofInfo) == 1 ? true : false;
    }

    public void reIndexUserFof(){
        CommandResult commandResult = ShellUtil.execCommand("/usr/bin/python2.6 /home/www/crontab/userFofIndex.py");
        System.out.println(commandResult.toString());
    }
}
